package com.example.demo.admin.controller;


import com.example.demo.common.file.service.FileService;
import com.example.demo.common.persistence.dao.SysDocFileMapper;
import com.example.demo.common.persistence.model.SysDocFile;
import com.example.demo.common.persistence.util.JsonUtil;
import com.example.demo.core.util.ExecTime;
import com.example.demo.core.util.JsonBean;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@RestController
public class UploadController {

    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    @Qualifier("ossFileService")
    private FileService fileService;

    @Autowired
    public SysDocFileMapper sysDocFileMapper;

    @RequestMapping("/upload")
    public void index(@RequestParam(value = "Filedata", required = false) MultipartFile file, String module1, String module2, String share, String expDate, HttpServletRequest request, HttpServletResponse response) {
        logger.info("文件上传");
        /*response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		response.setHeader("Access-Control-Allow-Headers","Access-Control");
		response.setHeader("Allow","POST");*/

        JsonBean jsonBean = new JsonBean();

        if (StringUtils.isEmpty(module1)) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("模块1不能为空!");
        }

        if (StringUtils.isEmpty(module2)) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("模块2不能为空!");
        }

        if (file == null || file.getSize() <= 0) {
            jsonBean.put("status", 0);
            jsonBean.setMessage("上传文件大小为空!");
        }

        if (StringUtils.isBlank(jsonBean.getMessage())) {
            long fileSize = file.getSize();
            String fileSizeStr = "";
            if (fileSize > 1024 * 1024) {
                fileSizeStr = (fileSize / 1024 / 1024) + "M";
            } else if (fileSize > 1024) {
                fileSizeStr = (fileSize / 1024) + "K";
            } else {
                fileSizeStr = (fileSize) + "B";
            }
            ExecTime execTime = new ExecTime();
            String fileId = fileService.putFile(file, module1, module2);

            logger.info("上传文件耗时:" + execTime + " fileName:" + file.getOriginalFilename() + " fileSize:" + fileSizeStr);

            jsonBean.put("status", 1);
            jsonBean.put("name", file.getName());
            jsonBean.put("url", fileId);
            jsonBean.put("fileName", file.getOriginalFilename());
            jsonBean.put("urlPath", fileService.getDownloadUrl(fileId));

            if (StringUtils.equalsIgnoreCase("true", share)) {
                SysDocFile sysDocFile = fileService.shareFile(fileId, expDate);
                jsonBean.put("fileAddress", sysDocFile.getFileAddress());
                jsonBean.put("accessCode", sysDocFile.getAccessCode());
            }

            try {
                CommonsMultipartFile mFile = (CommonsMultipartFile) file;
                DiskFileItem fileItem = (DiskFileItem) mFile.getFileItem();

                String ext = FilenameUtils.getExtension(mFile.getOriginalFilename());
                if (StringUtils.equalsIgnoreCase("etnd", ext)) {
                    String fileIds = fileService.tenderFile(fileItem.getStoreLocation().getAbsolutePath());

                    SysDocFile update = new SysDocFile();
                    update.setId(fileId);
                    update.setExtractFileId(fileIds);
                    sysDocFileMapper.updateById(update);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            String result = JsonUtil.toJSon(jsonBean);
            PrintWriter out = response.getWriter();

            out.println(result);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
